import { Store } from "../../core";

import StoreProps from "./types/StoreProps";
import useDocument from "./useDocument";
import useSearch from "./useSearch";
import { FC, ReactElement } from "react";

interface RenderSearchProps {
  clearKeyword(): void;
  changeMatchCase(matchCase: boolean): void;
  changeWholeWords(wholeWords: boolean): void;
  currentMatch: number;
  jumpToNextMatch(): void;
  jumpToPreviousMatch(): void;
  keyword: string;
  matchCase: boolean;
  numberOfMatches: number;
  wholeWords: boolean;
  search(): void;
  setKeyword(keyword: string): void;
}

type RenderSearch = (props: RenderSearchProps) => ReactElement;

export interface SearchProps {
  children: RenderSearch;
}

const Inner: FC<{
  children: RenderSearch;
  store: Store<StoreProps>;
}> = ({ children, store }) => {
  const result = useSearch(store);
  return children({ ...result });
};

const Search: FC<{
  children: RenderSearch;
  store: Store<StoreProps>;
}> = ({ children, store }) => {
  const { currentDoc } = useDocument(store);
  return currentDoc ? <Inner store={store}>{children}</Inner> : <></>;
};

export default Search;
